package com.top10.interceptor;

import com.alibaba.fastjson.JSON;
import com.top10.bean.JwtUtil;
import com.top10.bean.ResponseBean;

import com.top10.common.ResponseBeanCode;
import com.top10.common.WebConst;
import com.top10.entity.vo.JwtToken;
import com.top10.exception.RoleException;
import com.top10.utils.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class APIInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	@Lazy
	private JwtUtil jwtUtil;

	@Override
	public boolean preHandle(HttpServletRequest request,
							 HttpServletResponse response, Object handler) throws Exception {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;

		//验证是否登录（检查json token）
		if (RandomUtils.isBlank(httpServletRequest.getHeader(WebConst.TOKEN))) {
			// 返回JSON给请求方
			RandomUtils.writeJSONToResponse(httpServletResponse, JSON.toJSONString(

					ResponseBean.createError("[" + WebConst.TOKEN + "] 不能为空，请将token存入header")
			));
			return false;
		}
		String token = httpServletRequest.getHeader(WebConst.TOKEN);
		JwtToken jwtToken;
		try {
			jwtToken = jwtUtil.parseJwt(token);
		} catch (RoleException re) {//出现异常，说明验证失败
			ResponseBean responseBean = new ResponseBean();

			if (re.getMessage().equals(RoleException.MSG_TOKEN_ERROR)) {//token错误异常
				responseBean.setMessage(RoleException.MSG_TOKEN_ERROR).setCode(ResponseBeanCode.TOKEN_ERROR);
			} else {//token过期异常
				responseBean.setMessage(RoleException.MSG_TOKEN_OVERDUE).setCode(ResponseBeanCode.TOKEN_OVERDUE);
			}
			RandomUtils.writeJSONToResponse((HttpServletResponse) response, JSON.toJSONString(responseBean));//返回json
			return false;
		}
		if (jwtToken.getFlushed()) {//需要刷新token
			httpServletResponse.setHeader(WebConst.TOKEN, jwtToken.getToken());// 更新response
		}
		return true;
	}
}
